import {WeaTable} from 'comsRedux';
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import PropTypes from 'react-router/lib/PropTypes'
import {
    WeaTop,
    WeaTab,
    WeaLeftTree,
    WeaLeftRightLayout,
    WeaSearchGroup,
    WeaRightMenu,
	WeaPopoverHrm,
	WeaErrorPage,
	WeaTools
} from 'ecCom'
import {
	Button, Form, Modal
}
from 'antd'
import Immutable from 'immutable'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'

import CoworkConstant from '../constants/CoworkConstant';
import * as CollectApis from '../apis/collect';
import * as CollectAction from '../actions/collect'

const confirm = Modal.confirm;
const is = Immutable.is;
const createForm = Form.create;
const FormItem = Form.Item;
const WeaTableAction = WeaTable.action;

/**
 * 收藏的帖子页面
 */
class Collect extends React.Component {
	constructor(props) {
		super(props);
	}
	componentDidMount() {
		const { actions } = this.props;

        //初始化高级搜索区域
        actions.initConditionDatas();
        //初始化列表
        actions.doTableLoading();
	}
	componentWillReceiveProps(nextProps) {
    }
    componentWillUnmount() {
		//组件卸载时一般清理一些状态
		const { actions } = this.props;

		actions.setShowSearchAd(false);
		actions.saveSearchParamsFields();
    }
	render() {
		const { loading, title, actions, conditioninfo, showSearchAd,  fields, searchParamsAd, sessionkey } = this.props;
		return (
            <div className="wea-cowork-collect">
				<WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
					<WeaTop
						title="收藏的贴子"
						loading={loading}
						icon={CoworkConstant.icon}
						iconBgcolor={CoworkConstant.iconBgColor}
						buttons={ this.getTopButtons() }
						buttonSpace={10}
						showDropIcon={true}
						dropMenuDatas={this.getRightMenu()}
						onDropMenuClick={this.onRightMenuClick.bind(this)}
					>
						<WeaTab
							buttonsAd={this.getTabButtonsAd()}
							searchType={['base','advanced']}
							searchsBaseValue={searchParamsAd.remark}
							setShowSearchAd={bool=>{actions.setShowSearchAd(bool)}}
							showSearchAd={showSearchAd}
							hideSearchAd={()=> actions.setShowSearchAd(false)}
							searchsAd={<Form horizontal>{this.getSearchs()}</Form>}
							onSearch={ v => {actions.doTableLoading(searchParamsAd)} }
							onSearchChange={ v => { actions.saveSearchParamsFields({remark: {name: "remark", value: v}}) } }
						/>
						<WeaTable 
							loading={loading}
							sessionkey={sessionkey} 
							hasOrder={true} 
							needScroll={false}
							onOperatesClick={this.onOperatesClick.bind(this)}
							getColumns={ this.getNewColumns }
						/>
                	</WeaTop>
				</WeaRightMenu>
            </div>
		);
	}


	//右键菜单
    getRightMenu() {
		const { tabkey, sessionkey, comsWeaTable} = this.props;
		const moudleTablekey = sessionkey ? sessionkey.split('_')[0] : 'init';
		const moudleTableNow = comsWeaTable.get(moudleTablekey);
		const moudleSelectedRowKeys = moudleTableNow.get('selectedRowKeys');
		
		let btns = [];
        btns.push({
			key: 1,
            icon: <i className='icon-coms-search'/>,
            content: '搜索'
        });
        btns.push({
			key: 2,
			disabled: moudleSelectedRowKeys.toJS().length ? false : true,
            icon: <i className='icon-coms-Batch-delete'/>,
            content: '取消收藏'
		});
		btns.push({
			key: 3,
            icon: <i className='icon-coms-Custom'/>,
            content: '显示定制列'
		});
		/*
		btns.push({
			key: 4,
            icon: <i className='icon-coms-Custom'/>,
            content: '收藏'
		});
		btns.push({
			key: 5,
            icon: <i className='icon-coms-Custom'/>,
            content: '帮助'
		});
		*/
        return btns;
	}
	//右键菜单事件绑定
    onRightMenuClick(key) {
		const { actions, sessionkey, searchParamsAd } = this.props;
		if (key == 1) {
			actions.doTableLoading(searchParamsAd);
			actions.setShowSearchAd(false);
		} else if (key == 2) {
			this.batchCancelCollect();
		} else if (key == 3) {
			actions.setColSetVisible(sessionkey, true);
			actions.tableColSet(sessionkey, true)
		} 
		
	}
	//高级搜索group定义
    getSearchs() {
        return [
            (<WeaSearchGroup needTigger={true} title={this.getTitle()} showGroup={this.isShowFields()} items={this.getFields()}/>)
        ]
	}
	//高级搜索分组标题
	getTitle(index = 0) {
        const {conditioninfo} = this.props;
        return !isEmpty(conditioninfo) && conditioninfo[index].title
	}
	//高级搜索分组是否展示
    isShowFields(index = 0) {
        const {conditioninfo} = this.props;
        if(conditioninfo.length == 0){
            return true;
        }
        return !isEmpty(conditioninfo) && conditioninfo[index].defaultshow
    }
    // 0 常用条件，1 其他条件
    getFields(index = 0) {
        const {conditioninfo} = this.props;
        const fieldsData = !isEmpty(conditioninfo) && conditioninfo[index].items;
		let items = [];
        fieldsData && fieldsData.forEach( (field) => {
            items.push({
				com:(
					<FormItem
						label={`${field.label}`}
						labelCol={{span: `${field.labelcol}`}}
						wrapperCol={{span: `${field.fieldcol}`}}>
                    {WeaTools.getComponent(field.conditionType, field.browserConditionParam, field.domkey, this.props,field)}
                    </FormItem>),
                colSpan:1
			});
        });
        return items;
    }
	//高级搜索底部按钮定义
    getTabButtonsAd() {
        const { actions, searchParamsAd } = this.props;
        return [
            (<Button type="primary" onClick={()=>{actions.doTableLoading(searchParamsAd); actions.setShowSearchAd(false)}}>搜索</Button>),
            (<Button type="ghost" onClick={()=>{actions.saveSearchParamsFields()}}>重置</Button>),
            (<Button type="ghost" onClick={()=>{actions.setShowSearchAd(false)}}>取消</Button>)
        ]
	}
	
	//表格单元格转义
	onOperatesClick = (record, index, operate, flag) => {
		const { searchParamsAd } = this.props;
		//console.info("onOperatesClick", record, index, operate, flag);
		if(flag == 0) {
			//取消收藏
			let collectIds = record.cid;
			this.executeBatchCancelCollect(collectIds, searchParamsAd);
		}
	}
	//自定义过滤渲染
	getNewColumns(columns) {
        let newColumns = '';
        newColumns = columns.map(column => {
                let newColumn = column;
				newColumn.render = (text, record, index) => { //前端元素转义
					let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
					let url = "";
					if(newColumn.dataIndex == 'coworkname') {
						url = '/cowork/ViewCoWork.jsp?id=' + record.coworkid;
					} else if(newColumn.dataIndex == 'floorNum') {
						url = '/cowork/ViewCoWorkDiscuss.jsp?discussids=' + record.id;
					}
                    return(
						url == "" ?
							<div className="wea-url" dangerouslySetInnerHTML={{__html: valueSpan}} />
                        :
							<div className="wea-url-name" style={{cursor:'pointer'}} title={text} onClick={()=>{window.open(url)}} dangerouslySetInnerHTML={{__html: valueSpan}} />
                    )
                }
                return newColumn;
			});
		return columns;
	}

	//取消收藏
	batchCancelCollect() {
		const { actions, sessionkey, comsWeaTable, searchParamsAd } = this.props;
		const moudleTablekey = sessionkey ? sessionkey.split('_')[0] : 'init';
		const moudleTableNow = comsWeaTable.get(moudleTablekey);
		const moudleSelectedRowKeys = moudleTableNow.get('selectedRowKeys');
		let values = moudleSelectedRowKeys.toJS();
		this.executeBatchCancelCollect(values, searchParamsAd);
		
	}
	//执行取消收藏
	executeBatchCancelCollect(values, searchParamsAd) {
		const { actions } = this.props;
		confirm({
            title: '确认要取消收藏所选中的内容？',
            content: '',
            onOk() {
            	actions.cancelCoworkCollect({
					collectIds: values,
					searchParamsAd: searchParamsAd
				});
            },
            onCancel() {},
		});
	}

	// top中的按钮
	getTopButtons() {
		const { tabkey, sessionkey, comsWeaTable} = this.props;
		const moudleTablekey = sessionkey ? sessionkey.split('_')[0] : 'init';
		const moudleTableNow = comsWeaTable.get(moudleTablekey);
        const moudleSelectedRowKeys = moudleTableNow.get('selectedRowKeys');
		return [
				(<Button type="primary" disabled={moudleSelectedRowKeys.toJS().length ? false : true} onClick={this.batchCancelCollect.bind(this)}>取消收藏</Button>)
			];
	}

}


// form 表单与 redux 双向绑定
Collect = Form.create({
	onFieldsChange(props, fields) {
		props.actions.saveSearchParamsFields({...props.fields, ...fields});
	}, 
	mapPropsToFields(props) {
		return props.fields;
	}
})(Collect);

//组件检错机制
class MyErrorHandler extends React.Component {
	render() {
		const hasErrorMsg = this.props.error && this.props.error !== "";
		return(
			<WeaErrorPage msg={ hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" } />
		);
	}
}
Collect = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(Collect);

// 把 state map 到组件的 props 上
const mapStateToProps = state => {
	const { loading, title, actions, conditioninfo, showSearchAd, fields, searchParamsAd, sessionkey } = state.coworkCollect;
	const { comsWeaTable } = state;
	return { loading, title, actions, conditioninfo, showSearchAd,  fields, searchParamsAd, sessionkey, comsWeaTable };
	
}
// 把 dispatch map 到组件的 props 上
const mapDispatchToProps = dispatch => {
    return {
        actions: bindActionCreators({...CollectAction, ...WeaTableAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Collect);
